package cn.yc.inputstream;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {


    public static void main(String[] args) {

    }

    @Test
    public void readFile01() {
        String filePath = "e:\\io\\hello.txt";
        int readData = 0;
        java.io.FileInputStream fileInputStream = null;

        try {
            // 创建fileinputstream对象用于读取文件
            fileInputStream = new java.io.FileInputStream(filePath);
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char) readData); // 转成char显示
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                // 关闭文件流，释放资源
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 读取文件中汉字，用字节数组的形式提高读取效率
     */
    @Test
    public void readFile02() {
        String filePath = "e:\\io\\hello.txt";
        byte[] buf = new byte[8]; // 一次读8个字节
        Integer readLen = 0;
        java.io.FileInputStream fileInputStream = null;
        try {
            // 创建fileinputstream对象用于读取文件
            fileInputStream = new FileInputStream(filePath);
            while ((readLen = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readLen)); // 转成char显示
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                // 关闭文件流，释放资源
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
